#include <iostream>
#include <mysql/mysql.h>
#include <string>
#include <unistd.h>
const std::string host = "127.0.0.1";
const std::string user = "connection";
const std::string passwd = "123456";
const std::string db = "scott";
const unsigned int port = 3306;
int main()
{
    MYSQL *mysql = mysql_init(nullptr); // 初始化MySQL句柄
    if (nullptr == mysql)
    {
        std::cerr << "init MySQL error" << std::endl;
        return 1;
    }
    if (mysql_real_connect(mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr) // 连接MySQL数据库
    {
        std::cerr << "connect MySQL error" << std::endl;
        return 2;
    }
    mysql_set_character_set(mysql, "utf8"); // 设置字符集编码

    // std::string sql="update user set age='60' where id=3";
    std::string sql = "select * from user";
    int n = mysql_query(mysql, sql.c_str()); // 下发命令
    if (n == 0)
        std::cout << sql << "success" << std::endl;
    else
        std::cout << sql << "failed" << std::endl;

    // 保存结果集转储到res中
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        std::cerr << "mysql_store_result_error" << std::endl;
    }
    int rows = mysql_num_rows(res);     // 获取行数
    int fields = mysql_num_fields(res); // 获取列数

    std::cout << "行: " << rows << std::endl;
    std::cout << "列：" << fields << std::endl;

    // 获取列属性
    MYSQL_FIELD *fields_array = mysql_fetch_fields(res);
    for (int i = 0; i < fields; ++i)
    {
        std::cout << fields_array[i].name << "\t"; // 打印列名
    }
    std::cout << std::endl;

    for (int i = 0; i < rows; i++)
    {
        //row可以认为是一个char** 指针
        MYSQL_ROW row = mysql_fetch_row(res);//以行为单位获取记录
        for (int j = 0; j < fields; ++j)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << "\n";
    }
    std::cout << fields_array[0].db << " " << fields_array[0].table << std::endl;
    mysql_free_result(res);

    mysql_close(mysql);

    return 0;
}
